package com.easy.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class PermissionFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从Header中读取权限字符串
        String permissionHeader=request.getHeader("X-User-Permissions");
        if(permissionHeader!=null){
            //解析权限列表
            List<GrantedAuthority> authorityList= Arrays.stream(permissionHeader.split(","))
                    .map(permission->new SimpleGrantedAuthority(permission.trim()))
                    .collect(Collectors.toList());
            //构建Authentication
            Authentication authentication=new UsernamePasswordAuthenticationToken("user",null,authorityList);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request,response);
    }
}
